package com.ciwong.epaper.modules.bookstore.ui;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.bookstore.bean.BannerBean;
import com.ciwong.epaper.modules.epaper.bean.NewBook;
import com.ciwong.epaper.modules.epaper.ui.AllServiceOrBookActivity;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.libs.utils.CWLog;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/10/20.
 */

public class ItemAdvertisement extends LinearLayout implements View.OnClickListener {

	private Context context;
	private Banner banner;
	private NewBook mNewBook;
	private NewBook mHotBook;
	private TextView newbook_name;
	private TextView hotbook_name;
	private SimpleDraweeView hotbook_face;
	private SimpleDraweeView newbook_face;
	private ImageView img_banner_default;
	private List<BannerBean> mBannerBeanList;
	private LinearLayout mCircleIndicator;
	private List<ImageView> mIndicatorImages;
	private int lastposition = 0;
	private static final String TAG = "ItemAdvertisement";
	public ItemAdvertisement(Context context) {
		super(context);
		init();
		this.context = context;
	}


	protected void init() {
//		UI 分层
		LayoutInflater.from(this.getContext()).inflate(R.layout.item_advertisement, this);
		banner = (Banner) findViewById(R.id.ad_banner);
		//隐藏掉第三方指示器
		banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
		//设置banner动画效果
		banner.setBannerAnimation(Transformer.Default);
		//设置轮播时间
		banner.setDelayTime(3000);
		//设置图片加载器
		banner.setImageLoader(new GlideImageLoader());
		newbook_name = findViewById(R.id.newbook_name);
		hotbook_name = findViewById(R.id.hotbook_name);
		hotbook_face = findViewById(R.id.hotbook_face);
		newbook_face = findViewById(R.id.newbook_face);
		img_banner_default = findViewById(R.id.img_banner_default);
		mCircleIndicator = findViewById(R.id.mCircleIndicator);
		findViewById(R.id.ll_container_newbook).setOnClickListener(this);
		findViewById(R.id.ll_container_hotbook).setOnClickListener(this);
		banner.setOnBannerListener(new OnBannerListener() {
			@Override
			public void OnBannerClick(int position) {

				if (null != mBannerBeanList && position < mBannerBeanList.size()) {

					CWLog.d("BookstoreFragment", "############position##############" + position);
					//linktype为2时跳转到链接地址
					if (mBannerBeanList.get(position).getLinkType() == 2) {
						if (!TextUtils.isEmpty(mBannerBeanList.get(position).getLinkAddress())) {
							CWLog.d("itemadfragment", "acitivity" + (Activity) getContext());
							EpaperJumpManager.jumpToBannerAdActivity(R.string.go_back, (Activity) getContext(), mBannerBeanList.get(position), 10);
						}
					} else {
						// 外面不区分，里面区分
						MeJumpManager.jumpBuyService((Activity) getContext(), R.string.go_back, mBannerBeanList.get(position).getServiceId(), -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, null);
					}
				}

			}
		});
		mIndicatorImages = new ArrayList<>();

	}

	/**
	 * 初始化指示器
	 *
	 * @param context
	 */
	private void createIndicator(Context context) {
		mIndicatorImages.clear();
		mCircleIndicator.removeAllViews();
		if (null != mBannerBeanList && 0 < mBannerBeanList.size()) {
			for (int i = 0; i < mBannerBeanList.size(); i++) {
				ImageView imageView = new ImageView(context);
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DisplayUtils.dip2px(context, 10), DisplayUtils.dip2px(context, 2));
				params.leftMargin = DisplayUtils.dip2px(context, 5);
				params.rightMargin = DisplayUtils.dip2px(context, 5);
				if (i == 0) {
					imageView.setImageResource(R.drawable.rb_select_shape);
				} else {
					imageView.setImageResource(R.drawable.rb_default_shape);
				}
				mIndicatorImages.add(imageView);
				mCircleIndicator.addView(imageView, params);
			}
		}
	}


	public void update(List<BannerBean> bannerBeanList, NewBook newBook, NewBook hotBook) {
		mNewBook = newBook;
		mHotBook = hotBook;
		mBannerBeanList = bannerBeanList;

		if (null != mNewBook) {
			if (!TextUtils.isEmpty(mNewBook.getLogo())) {
				CWLog.d("mnewbook", "####salestypeddd####" + mNewBook.getSalesType());
				ViewGroup.LayoutParams layoutParams = newbook_face.getLayoutParams();
				if (mNewBook.getSalesType() == 0&&mNewBook.getServiceId()!=0) {//服务
					layoutParams.height = DisplayUtils.dip2px(getContext(), 60);
					CWLog.e(TAG, "update: mNewBook 服务" );
				} else if (mNewBook.getSalesType() == 1) {//书籍
					layoutParams.height = DisplayUtils.dip2px(getContext(), 86);
					CWLog.e(TAG, "update: mNewBook 书籍" );
				}else{
					layoutParams.height = DisplayUtils.dip2px(getContext(), 86);
				}
				newbook_face.setLayoutParams(layoutParams);
				Uri uri = Uri.parse(mNewBook.getLogo());
				setNetImg(newbook_face, uri);
			}

			newbook_name.setText(mNewBook.getServiceName());
		}

		if (null != mHotBook) {
			if (!TextUtils.isEmpty(mHotBook.getLogo())) {
				CWLog.d("hotbook", "####salestypeddd####" + mHotBook.getSalesType());
//				RoundingParams bitmapOnlyParams = RoundingParams.fromCornersRadius(10) .setRoundingMethod(RoundingParams.RoundingMethod.BITMAP_ONLY);
//				hotbook_face.getHierarchy().setRoundingParams(bitmapOnlyParams);
//				hotbook_face.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER);
				ViewGroup.LayoutParams layoutParams = hotbook_face.getLayoutParams();
				if (mHotBook.getSalesType() == 0&&mHotBook.getServiceId()!=0) {//服务
					layoutParams.height = DisplayUtils.dip2px(getContext(), 60);
					CWLog.e(TAG, "update: mHotBook 服务" );

				} else if (mHotBook.getSalesType() == 1) {//书籍
					layoutParams.height = DisplayUtils.dip2px(getContext(), 86);
					CWLog.e(TAG, "update: mHotBook 书籍" );
				} else{
					layoutParams.height = DisplayUtils.dip2px(getContext(), 86);
				}
				Uri uri = Uri.parse(mHotBook.getLogo());
//				hotbook_face.setImageURI(uri);
				setNetImg(hotbook_face, uri);
			}
			hotbook_name.setText(mHotBook.getServiceName());
		}


		if (null != bannerBeanList && bannerBeanList.size() > 0) {
			List<String> urlList = new ArrayList<>();

			for (int i = 0; i < bannerBeanList.size(); i++) {
				urlList.add(bannerBeanList.get(i).getPhoto());
			}
			banner.setImages(urlList);
			banner.start();
			img_banner_default.setVisibility(GONE);


			mCircleIndicator.setVisibility(VISIBLE);
			createIndicator(context);
			banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
				@Override
				public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

				}

				@Override
				public void onPageSelected(int position) {
					CWLog.d("onPageSelected", "############position##############" + position);
					if (null != mBannerBeanList && 0 < mBannerBeanList.size()) {
						if (mBannerBeanList.size() == 1) {
							mCircleIndicator.setVisibility(GONE);
//							mIndicatorImages.get(position).setImageResource(R.drawable.rb_select_shape);
						} else {
							mIndicatorImages.get((lastposition + mBannerBeanList.size()) % mBannerBeanList.size()).setImageResource(R.drawable.rb_default_shape);
							mIndicatorImages.get((position + mBannerBeanList.size()) % mBannerBeanList.size()).setImageResource(R.drawable.rb_select_shape);
							lastposition = position;
						}
					}
				}

				@Override
				public void onPageScrollStateChanged(int state) {

				}
			});
		} else {
			mCircleIndicator.setVisibility(GONE);
			img_banner_default.setVisibility(VISIBLE);
		}


	}

	private void setNetImg(SimpleDraweeView simpleDraweeView, Uri uri) {
		ImageRequest request = null;
		if (uri != null) {
			request = ImageRequestBuilder.newBuilderWithSource(uri)
					.setResizeOptions(new ResizeOptions(DisplayUtils.dip2px(getContext(), 300), DisplayUtils.dip2px(getContext(), 420)))
					.build();
			RoundingParams bitmapOnlyParams = RoundingParams.fromCornersRadius(10)
					.setRoundingMethod(RoundingParams.RoundingMethod.OVERLAY_COLOR)
					.setOverlayColor(Color.WHITE);
			GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(getResources());
//			builder.setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER);
			builder.setRoundingParams(bitmapOnlyParams);
			GenericDraweeHierarchy hierarchy = builder.build();
			simpleDraweeView.setHierarchy(hierarchy);
			DraweeController drawweeController = Fresco.newDraweeControllerBuilder()
					.setUri(uri)
					.setImageRequest(request)
					//列表滑动会变流畅
					.setOldController(simpleDraweeView.getController())
					.build();
			simpleDraweeView.setController(drawweeController);
		}
	}

	@Override
	public void onClick(View view) {
		int id = view.getId();

		if (id == R.id.ll_container_newbook) {

			EpaperJumpManager.jumpToAllServiceOrBook(R.string.go_back, (Activity) getContext(), AllServiceOrBookActivity.TYPE_NEW_BOOK, 0, null);

		} else if (id == R.id.ll_container_hotbook) {
			EpaperJumpManager.jumpToAllServiceOrBook(R.string.go_back, (Activity) getContext(), AllServiceOrBookActivity.TYPE_HOT_RECOMMEND, 0, null);
		}

	}


	public class GlideImageLoader extends ImageLoader {
		@Override
		public void displayImage(Context context, Object path, ImageView imageView) {
			/**
			 注意：
			 1.图片加载器由自己选择，这里不限制，只是提供几种使用方法
			 2.返回的图片路径为Object类型，由于不能确定你到底使用的那种图片加载器，
			 传输的到的是什么格式，那么这种就使用Object接收和返回，你只需要强转成你传输的类型就行，
			 切记不要胡乱强转！
			 */

			//Glide 加载图片简单用法
//            Glide.with(context).load(path).into(imageView);

			//Picasso 加载图片简单用法
//            Picasso.with(context).load(path).into(imageView);


			//用fresco加载图片简单用法，记得要写下面的createImageView方法
			Uri uri = Uri.parse((String) path);
			imageView.setImageURI(uri);
		}

		//提供createImageView 方法，如果不用可以不重写这个方法，主要是方便自定义ImageView的创建
		@Override
		public ImageView createImageView(Context context) {
			//使用fresco，需要创建它提供的ImageView，当然你也可以用自己自定义的具有图片加载功能的ImageView
			SimpleDraweeView simpleDraweeView = new SimpleDraweeView(context);
			simpleDraweeView.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY);
			return simpleDraweeView;
		}
	}


}
